package controllers

import (
	"admin-glm-go/internal/models"
	"admin-glm-go/internal/response"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

// LinkListRequest 友情链接列表请求参数
type LinkListRequest struct {
	Page     int    `form:"page"`
	PageSize int    `form:"pageSize"`
	Name     string `form:"name"`
	Status   int    `form:"status"`
}

// AddLinkRequest 添加友情链接请求参数
type AddLinkRequest struct {
	Name        string `json:"name" binding:"required"`
	Url         string `json:"url" binding:"required"`
	Logo        string `json:"logo"`
	Description string `json:"description"`
	Sort        int    `json:"sort"`
	Status      int    `json:"status"`
}

// UpdateLinkRequest 更新友情链接请求参数
type UpdateLinkRequest struct {
	ID          uint64 `json:"id" binding:"required"`
	Name        string `json:"name" binding:"required"`
	Url         string `json:"url" binding:"required"`
	Logo        string `json:"logo"`
	Description string `json:"description"`
	Sort        int    `json:"sort"`
	Status      int    `json:"status"`
}

// FriendshipLinkController 友情链接控制器
type FriendshipLinkController struct {
	db *gorm.DB
}

// NewFriendshipLinkController 创建友情链接控制器
func NewFriendshipLinkController(db *gorm.DB) *FriendshipLinkController {
	return &FriendshipLinkController{db: db}
}

// GetLinkList 获取友情链接列表
// @Summary 获取友情链接列表
// @Description 获取友情链接列表
// @Tags 友情链接管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param name query string false "链接名称"
// @Param status query int false "状态"
// @Success 200 {object} response.Response
// @Router /links/list [get]
func (ctrl *FriendshipLinkController) GetLinkList(c *gin.Context) {
	var req LinkListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	// 构建查询条件
	query := ctrl.db.Model(&models.FriendshipLink{})
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Status != 0 {
		query = query.Where("status = ?", req.Status)
	}

	// 获取总数
	var total int64
	query.Count(&total)

	// 分页查询
	var links []models.FriendshipLink
	offset := (req.Page - 1) * req.PageSize
	err := query.Offset(offset).Limit(req.PageSize).Order("sort ASC, id DESC").Find(&links).Error
	if err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	response.Success(c, gin.H{
		"total":  total,
		"records": links,
	})
}

// GetAllLinks 获取所有友情链接
// @Summary 获取所有友情链接
// @Description 获取所有友情链接（不包含分页）
// @Tags 友情链接管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} response.Response
// @Router /links/all [get]
func (ctrl *FriendshipLinkController) GetAllLinks(c *gin.Context) {
	var links []models.FriendshipLink
	err := ctrl.db.Model(&models.FriendshipLink{}).
		Select("id", "name", "url", "logo").
		Where("status = ?", 1).
		Order("sort ASC").
		Find(&links).Error

	if err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, links)
}

// AddLink 添加友情链接
// @Summary 添加友情链接
// @Description 添加友情链接
// @Tags 友情链接管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body AddLinkRequest true "友情链接信息"
// @Success 200 {object} response.Response
// @Router /links/add [post]
func (ctrl *FriendshipLinkController) AddLink(c *gin.Context) {
	var req AddLinkRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 获取当前管理员ID（从JWT中获取）	
	adminID, exists := c.Get("userId")
	if !exists {
		response.Error(c, 401, "未授权访问")
		return
	}

	adminIDUint64, ok := adminID.(uint64)
	if !ok {
		response.ServerError(c)
		return
	}

	// 创建友情链接
	link := models.FriendshipLink{
		Name:        req.Name,
		Url:         req.Url,
		Logo:        req.Logo,
		Description: req.Description,
		Sort:        req.Sort,
		Status:      req.Status,
		CreateTime:  time.Now(),
		UpdateTime:  time.Now(),
		CreatedBy:   &adminIDUint64,
		UpdatedBy:   &adminIDUint64,
	}

	if err := ctrl.db.Create(&link).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// UpdateLink 更新友情链接
// @Summary 更新友情链接
// @Description 更新友情链接
// @Tags 友情链接管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body UpdateLinkRequest true "友情链接信息"
// @Success 200 {object} response.Response
// @Router /links/update [put]
func (ctrl *FriendshipLinkController) UpdateLink(c *gin.Context) {
	var req UpdateLinkRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 检查友情链接是否存在
	var link models.FriendshipLink
	if err := ctrl.db.First(&link, req.ID).Error; err != nil {
		response.Error(c, 404, "友情链接不存在")
		return
	}

	// 获取当前管理员ID（从JWT中获取）	
	adminID, exists := c.Get("userId")
	if !exists {
		response.Error(c, 401, "未授权访问")
		return
	}

	adminIDUint64, ok := adminID.(uint64)
	if !ok {
		response.ServerError(c)
		return
	}

	// 更新友情链接
	link.Name = req.Name
	link.Url = req.Url
	link.Logo = req.Logo
	link.Description = req.Description
	link.Sort = req.Sort
	link.Status = req.Status
	link.UpdateTime = time.Now()
	link.UpdatedBy = &adminIDUint64

	if err := ctrl.db.Save(&link).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// DeleteLink 删除友情链接
// @Summary 删除友情链接
// @Description 删除友情链接
// @Tags 友情链接管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "友情链接ID"
// @Success 200 {object} response.Response
// @Router /links/delete/{id} [delete]
func (ctrl *FriendshipLinkController) DeleteLink(c *gin.Context) {
	id := c.Param("id")

	// 检查友情链接是否存在
	var link models.FriendshipLink
	if err := ctrl.db.First(&link, id).Error; err != nil {
		response.Error(c, 404, "友情链接不存在")
		return
	}

	// 删除友情链接
	if err := ctrl.db.Delete(&link).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}